<template>
    <div>
        <div class='container'>
            <div class='handle-box'>
                商品编号：
                <el-input v-model='query.productCodeOrName' placeholder='商品编号' class='handle-input mr10'
                          style='width: 150px'
                          prefix-icon='el-icon-search'></el-input>

                <el-button type='primary' icon='el-icon-search' @click='handleSearch'>搜索</el-button>
                <el-button type='primary' icon='el-icon-refresh-left' @click='resetSearch'>重置</el-button>
            </div>

            <div style='margin-bottom: 20px'>
                <el-button type='danger' class='el-icon-delete' @click='handleBatchDelete()'>删除选中产品</el-button>
                <el-button type='primary' class='el-icon-message' @click='truncateCart()'>清空购物车</el-button>
            </div>

            <el-table
                :data='tableData'
                border
                :summary-method='getSummaries'
                show-summary
                class='table'
                ref='multipleTable'
                header-cell-class-name='table-header'
                @selection-change='handleSelectionChange'
            >
                <el-table-column type='selection' width='55' align='center'></el-table-column>
                <el-table-column type='index' width='55' label='序号' align='center'></el-table-column>
                <el-table-column prop='productId' label='商品主键' align='center' v-if=false></el-table-column>
                <el-table-column
                    prop='productUrl'
                    label='商品图片'
                    align='center'
                >
                    <template width='90' slot-scope='scope'>
                        <img style='width:80px;height:80px;border:none;' :src='scope.row.productUrl'>
                    </template>
                </el-table-column>
                <el-table-column prop='productCode' label='商品编码' align='center'></el-table-column>
                <el-table-column prop='productName' label='商品名称' align='center'></el-table-column>
                <el-table-column prop='stock' label='库存' align='center'>
                    <template slot-scope='scope'>{{ scope.row.stock | stockFilter }}</template>
                </el-table-column>
                <el-table-column prop='speck' label='单位' align='center'></el-table-column>
                <el-table-column prop='num' label='购买数量' align='center' width='180'>
                    <template width='10' slot-scope='scope'>
                        <el-input-number v-model='scope.row.num' @change='handleNumberChange(scope.$index, scope.row)'
                                         :min='1' :max='9999'
                                         label='描述文字'></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop='productMoney' label='商品单价格（元）' align='center' type='number'>
                    <template slot-scope='scope'>
                         <span style='color: sandybrown'>
                    {{ scope.row.productMoney | priceFilter }}
                         </span>
                    </template>
                </el-table-column>
                <el-table-column prop='productTotalMoney' label='商品价格（元）' align='center' type='number'>
                    <template slot-scope='scope'>
                        <span style='color: sandybrown'>
                        {{ scope.row.productMoney * scope.row.num | priceFilter }}
                        </span>
                    </template>
                </el-table-column>


                <!--工具栏-->
                <el-table-column label='操作' width='180' align='center'>
                    <template slot-scope='scope'>
                        <el-button
                            type='text'
                            icon='el-icon-delete'
                            class='red'
                            @click='handleDelete(scope.$index, scope.row)'
                        >移出购物车
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div style='margin-bottom: 20px;margin-top: 20px;margin-right: 20px'>
                <el-button type='warning' @click='saveOrder()'>去结算</el-button>
            </div>

        </div>
        <!--        <add-email ref='addEmailDialog' @get-data='getData'></add-email>-->
        <!--        <detail-email ref='detailEmailDialog' @get-data='getData'></detail-email>-->
    </div>
</template>

<script>
import { fetchData } from '../../api';


export default {
    name: 'cartTable',
    components: {},
    data() {
        return {
            query: {
                productCodeOrName: '',//商品编号
                userId: ''//用户ID
            },
            tableData: [],//数据表格数据
            pageTotal: 0,//分页总数
            multipleSelection: [],//多选值
            totalMoney: 0
        };
    },
    //初始化函数
    mounted() {
        this.getData();
    },
    //过滤器
    filters: {
        priceFilter(d) {
            return '￥' + d.toFixed(2);
        },
        stockFilter(d) {
            if (d == undefined || d == null) {
                return 0;
            }
            return d;
        }
    },
    //计算器
    computed: {
        // totalMoney(){
        //     var n=0;
        //     this.items.forEach()
        // }
    },
    methods: {
        // 给数据表格赋值
        getData: function() {
            this.$http.post(this.global.BASIC_SERVER + '/productController/showCart.json', this.query).then(res => {
                if (res.data.status) {
                    if (res.data.data != null) {
                        this.tableData = res.data.data.cartItemVos;
                    }
                    this.$message.success(res.data.msg);
                }
            });
        },
        //订单结算
        saveOrder() {
            const param = new Object();
            const list = new Array();
            const data = this.multipleSelection;
            if (data.length < 1) {
                this.$message.error('最少选择一个商品!');
            } else {
                for (const item of data) {
                    const obj = new Object();
                    obj.productId = item['productId'];
                    obj.productMoney = item['productMoney'];
                    obj.num = item['num'];
                    list.push(obj);
                }
                param.saveOrderItemRequestList = list;
                this.$http.post(this.global.BASIC_SERVER + '/orderController/saveOrder.json', param).then(res => {
                    if (res.data.status) {
                        this.$message.success('选购成功！如有库存数不足的商品，以为您按最大购买量进行购买，请及时支付！');
                        this.getData();
                    }
                });
            }
        },
        //购物车数量变化
        handleNumberChange(index, row) {
            const param = new Object();
            param.productId = row.productId;
            param.num = row.num;
            this.$http.post(this.global.BASIC_SERVER + '/productController/changeCartItemNum.json', param).then(res => {
                // if (res.data.status) {
                //     this.getData();
                // }
            });
        },
        //移出购物车
        handleDelete(index, row) {
            const productIds = new Array();
            productIds.push(row.productId);
            this.$http.post(this.global.BASIC_SERVER + '/productController/deleteCartItem.json', productIds).then(res => {
                if (res.data.status) {
                    this.getData();
                }
            });
        },
        //批量删除商品
        handleBatchDelete() {
            const data = this.multipleSelection;
            const productIds = new Array();
            if (data.length < 1) {
                this.$message.error('请至少选择一个商品');
            }
            for (const item of data) {
                productIds.push(item['productId']);
            }
            this.$http.post(this.global.BASIC_SERVER + '/productController/deleteCartItem.json', productIds).then(res => {
                if (res.data.status) {
                    this.getData();
                }
            });
        },
        //清空购物车
        truncateCart() {
            // 二次确认删除
            this.$confirm('确定要清空购物车吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.$http.get(this.global.BASIC_SERVER + '/productController/deleteAllCartItem.json').then(res => {
                        if (res.data.status) {
                            this.getData();
                        }
                    });
                });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 0);//重置为首页
            this.getData();//重新请求赋值
        },

        // 触发重置按钮
        resetSearch() {
            this.query.productCodeOrName = '';
            this.$set(this.query, 'pageIndex', 0);//重置为首页
            this.getData();//重新请求赋值
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //购物车合计
        getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            let totalMoney = 0;
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总价';
                    return;
                }
                //只返回总金额
                if (column.property != 'productTotalMoney') {
                    sums[index] = '';
                    return;
                }
                //遍历值
                const data = this.multipleSelection;
                if (data.length == 0) {
                    sums[index] = 0 + '元';
                    return;
                }

                const value = data.map(item => {
                    console.log(item);
                    const money = Number(item['num']) * Number(item['productMoney']);
                    return money;
                });
                for (let i = 0; i < value.length; i++) {
                    totalMoney += value[i];
                }
                return sums[index] = totalMoney.toFixed(2) + '元';
            });
            return sums;
        }
        //样式
        // needStyle(column) {
        //     let cellStyle;
        //     if (column.column.property != 'productTotalMoney') {
        //         return;
        //     }
        //     cellStyle = 'color:red';
        //     return cellStyle;
        // }
    }
};
</script>

<style scoped>
/deep/ .el-table .el-table__footer-wrapper .cell {
    text-align: center;
    color: red;
}

.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.yellow {
    color: #E6A23C;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
